package org.example.projecttwo.service.Impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.projecttwo.entity.Collection;
import org.example.projecttwo.entity.dto.content.request.CollectionDTO;
import org.example.projecttwo.entity.dto.content.response.CollectionVO;
import org.example.projecttwo.mapper.CollectionMapper;
import org.example.projecttwo.service.ICollectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 收藏表 服务实现类
 * </p>
 *
 * @author nn
 * @since 2025-11-01
 */
@Service
public class CollectionServiceImpl extends ServiceImpl<CollectionMapper, Collection> implements ICollectionService {

    @Autowired
    private CollectionMapper collectionMapper;

    @Override
    public IPage<CollectionVO> pageByUserWithSearch(
            Long userId,
            Integer contentType,
            String keyword,
            Long current,
            Long size) {
        Page<CollectionVO> page = new Page<>(current, size);
        return collectionMapper.selectPageByUserWithSearch(page, userId, contentType, keyword);
    }

    @Override
    public CollectionVO getDetailById(Long id) {
        return collectionMapper.selectDetailById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Collection createCollection(CollectionDTO dto) {
        // 检查是否已收藏
        boolean isCollected = checkCollection(dto.getUserId(), dto.getContentType(), dto.getContentId());
        if (isCollected) {
            throw new RuntimeException("已收藏该内容，无需重复收藏");
        }

        // 创建收藏记录
        Collection collection = new Collection();
        collection.setUserId(dto.getUserId());
        collection.setContentType(dto.getContentType());
        collection.setContentId(dto.getContentId());
        // createTime由MyBatis-Plus自动填充
        collectionMapper.insert(collection);

        return collection;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeCollection(CollectionDTO dto) {
        collectionMapper.deleteByUserContent(
                dto.getUserId(),
                dto.getContentType(),
                dto.getContentId()
        );
    }

    @Override
    public boolean checkCollection(Long userId, Integer contentType, Long contentId) {
        Integer count = collectionMapper.countByUserContent(userId, contentType, contentId);
        return count != null && count > 0;
    }

    @Override
    public int countByContent(Integer contentType, Long contentId) {
        return collectionMapper.countByContent(contentType, contentId);
    }
}